package cn.jinjimi.app.main.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.GridLayoutManager;

import cn.jinjimi.app.main.widget.CommonRV.IUserAction;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTraceParam;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.ShareProxy;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.bean.EventDataField;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.bean.Source;
import cn.jinjimi.app.controller.event.LocalEvent.ReaderShareEvent;
import cn.jinjimi.app.interfaces.ILoadDataListener;
import cn.jinjimi.app.poster.bean.PosterInfo;
import cn.jinjimi.app.poster.fragment.PosterContainerFragment;
import cn.jinjimi.app.poster.interfaces.IPosterLoadMore;
import cn.jinjimi.app.reader.ArticlePresenter;
import cn.jinjimi.app.reader.ReaderAdapter;
import cn.jinjimi.app.reader.bean.ArticleData;
import cn.jinjimi.app.reader.bean.ArticleViewData;
import cn.jinjimi.app.reader.bean.JinjuViewData;
import cn.jinjimi.app.reader.bean.PosterInfos;
import cn.jinjimi.app.reader.bean.ShareInfo;
import cn.jinjimi.framework.router.Router;
import cn.jinjimi.app.main.activity.ArticleSearchActivity;
import cn.jinjimi.app.main.activity.ReaderDetailActivity;
import cn.jinjimi.app.main.dialog.ShareDialog;
import cn.jinjimi.app.main.dialog.SharePosterDialog;
import cn.jinjimi.app.main.extend.BaseNetControlFragment;
import cn.jinjimi.app.main.widget.CommonRV.IActionListener;
import cn.jinjimi.app.main.widget.CommonRV.IViewData;
import cn.jinjimi.app.main.widget.CommonRV.NoMoreViewData;
import cn.jinjimi.app.main.widget.XRecyclerView.XRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * Created by lforxeverc on 2017/4/14.
 */

public class ReaderArticleListFragment extends BaseNetControlFragment implements IActionListener,
        ILoadDataListener<List<IViewData>>, XRecyclerView.LoadingListener {
    public static final int TYPE_RECOMMEND = 0; //推荐
    public static final int TYPE_ALL_ARTICLE = 1; //好文

    private XRecyclerView mRecyclerView;
    private ReaderAdapter<IViewData> mAdapter;
    private int type;
    private int page = ArticlePresenter.DEFAULT_PAGE;
    private ArticlePresenter<List<IViewData>> mPresenter;

    public static ReaderArticleListFragment create(int type) {
        ReaderArticleListFragment f = new ReaderArticleListFragment();
        Bundle b = new Bundle();
        b.putInt(BundleKey.TYPE, type);
        f.setArguments(b);
        return f;
    }

    @Override
    protected int getBizLayoutResourceId() {
        return R.layout.fragment_article_list;
    }

    @Override
    protected void initialBiz() {
        type = getArguments().getInt(BundleKey.TYPE);
        mRecyclerView = (XRecyclerView) findView().findViewById(R.id.recyclerview);

        mAdapter = new ReaderAdapter(getContext(), this);

        GridLayoutManager glm = new GridLayoutManager(getContext(), 2);
        mRecyclerView.setLayoutManager(glm);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLoadingMoreEnabled(false);
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setLoadingListener(this);

        mPresenter = new ArticlePresenter<>(type, this);
        mAdapter.setItems(mPresenter.getCacheData());
    }

    @Override
    protected void loadData() {
        mPresenter.loadData(page);
    }

    @Override
    public void onUserAction(final IUserAction action) {
        final IViewData data = action.getData();
        switch (action.getAction()) {
            case IUserAction.ACTION_ARTICLE_VIEW:
                if (!(data instanceof ArticleData)) return;

                if (type == TYPE_ALL_ARTICLE) {
                    analyAllArticleClick(((ArticleData) data).getId(), action.getPosition() - 1);
                } else if (type == TYPE_RECOMMEND) {
                    analyRecommClick(((ArticleData) data).getId(), action.getPosition());
                }
                Intent intent = new Intent(getContext(), ReaderDetailActivity.class);
                intent.putExtra(BundleKey.ARTICLE_ID, ((ArticleData) data).getId());
                intent.putExtra(BundleKey.SOURCE, type == TYPE_ALL_ARTICLE ? Source.APP_READER_ARTICLELIST : Source.APP_READER_RECOMMEND_ARTICLE);
                startActivity(intent);

                mPresenter.hasViewArticle(((ArticleData) data).getId());
                ((ArticleData) data).setHasRead(true);
                mAdapter.updateItem(action.getPosition(), data);
                break;
            case IUserAction.ACTION_ARTICLE_SEARCH:
                startActivity(new Intent(getContext(), ArticleSearchActivity.class));
                break;
            case IUserAction.ACTION_SHOW_JINJU:
                if (!AccountManager.getInstance().isLogin()) {
                    Router.doLogin(getContext());
                    return;
                }

                analyRecommClick(((ArticleData) data).getId(), action.getPosition());

                if (!(data instanceof JinjuViewData)) return;
                final PosterInfos posterInfos = mAdapter.getPostInfosAt(action.getPosition());
                SharePosterDialog sharePosterDialog = new SharePosterDialog();
                sharePosterDialog.setContext((FragmentActivity) getContext());
                sharePosterDialog.setSource(Source.APP_READER_RECOMMEND_QUOTE);
                sharePosterDialog.setListener(new IPosterLoadMore() {
                    @Override
                    public void reqLoadPage(int page) {

                    }

                    @Override
                    public PosterInfo fetchPosterInfoWithPosition(int position) {
                        return posterInfos.getDatas().get(position);
                    }

                    @Override
                    public void updatePostInfo(PosterInfo info, int position) {
                        posterInfos.getDatas().set(position, info);
                    }
                });
                sharePosterDialog.setInfos(posterInfos.getPosition(), posterInfos.getDatas().size());
                sharePosterDialog.setCategoryCode(PosterContainerFragment.DataType.JINJU_POSTER);
                getChildFragmentManager().beginTransaction().add(sharePosterDialog, "JINJU").commitAllowingStateLoss();
                break;
            default:break;
        }
    }

    @Override
    public void onLoadSuccess(int page, List<IViewData> mDatas, boolean hasMore) {
        this.page = page;
        if (!hasMore && mDatas != null) {
            if (!(page == ArticlePresenter.DEFAULT_PAGE && mDatas.isEmpty()))
                mDatas.add(new NoMoreViewData(getString(R.string.nomore_loading)));
        }
        if (page == ArticlePresenter.DEFAULT_PAGE) {
            netLoadSucc();
            mRecyclerView.setRefreshTime(System.currentTimeMillis());
            mAdapter.setItems(mDatas);
        } else {
            mAdapter.addItems(mDatas);
        }
        mRecyclerView.refreshComplete();
        mRecyclerView.loadMoreComplete();
        mRecyclerView.setLoadingMoreEnabled(hasMore);
    }

    @Override
    public void onLoadFail(int page, String errMsg) {
        mRecyclerView.reset();
        if (page == ArticlePresenter.DEFAULT_PAGE) {
            int count = mAdapter.getItemCount();
            if (count == 0) {
                netLoadFaiEmpty();
            } else {
                netLoadSucc();
            }
        }
        ToastUtils.toastMessage(getContext(), R.string.load_fail);
    }

    @Override
    public void onRefresh() {
        mPresenter.loadData(ArticlePresenter.DEFAULT_PAGE);
    }

    @Override
    public void onLoadMore() {
        mPresenter.loadData(page + 1);
    }

    @Override
    public void onDestroy() {
        if (mPresenter != null && mAdapter != null) {
            mPresenter.cacheData(mAdapter.getItems());
        }
        super.onDestroy();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            // 10分钟自动刷新
            if (mRecyclerView != null) {
                if (System.currentTimeMillis() - mRecyclerView.getRefreshTime() > Constants.MIN_10) {
                    mPresenter.loadData(page);
                }
            }
        }
    }

    private void analyArticleShare(@EventTraceParam(EventDataField.ParamTo) String id, @EventTraceParam(value = EventDataField.ParamPostion, isValueAutoPlusOne = true) int position,
                                   @EventTraceParam(value = EventDataField.ParamFrom, selector = {EventID.FROM_APP_ALL, EventID.FROM_APP_RECOMMEND}) boolean fromAll) {
    }

    private void analyAllArticleClick(@EventTraceParam(EventDataField.ParamId) String id, @EventTraceParam(value = EventDataField.ParamPostion, isValueAutoPlusOne = true) int position) {
    }

    private void analyRecommClick(@EventTraceParam(EventDataField.ParamId) String id, @EventTraceParam(value = EventDataField.ParamPostion, isValueAutoPlusOne = true) int position) {
    }

    public void onReceiveEvent(ReaderShareEvent event) {
        String id = event.getId();
        ReaderShareEvent.State state = event.getState();
        if (AccountManager.getInstance().isLogin() && state == ReaderShareEvent.State.SUCCESS && mAdapter != null && mAdapter.getItemCount() > 0) {
            for (IViewData data : mAdapter.getItems()) {
                if (data instanceof ArticleViewData) {
                    String curId = ((ArticleViewData) data).getId();
                    if (curId.equals(id)) {
                        ((ArticleData) data).setShareInfo(new ShareInfo(System.currentTimeMillis(), AccountManager.getInstance().getAccount().realName));
                        mAdapter.updateItem(mAdapter.getItems().indexOf(data), data);
                        break;
                    }
                }
            }

        }
    }
}
